package fr.cnam.ratpProject.server;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import fr.cnam.ratpProject.client.services.ReseauRatpService;
import fr.cnam.ratpProject.sharedDatas.Etape;
import fr.cnam.ratpProject.sharedDatas.Ligne;
import fr.cnam.ratpProject.sharedDatas.Station;

@SuppressWarnings("serial")
public class ReseauRatpServiceImpl extends AbstractServiceImpl implements ReseauRatpService{
 
	@Override
	public ArrayList<Station> getAllStations() {
		Statement stmt1 = jdbc.getStatement();
		String sql = "Select * from Station;";
		ArrayList<Station> result = new ArrayList<Station>();
		ResultSet rs;
		try {
			rs = stmt1.executeQuery(sql);

			while(rs.next()){
				Station s = new Station();
				s.setName(rs.getString("nomStation"));
				result.add(s);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return result;
	}

	@Override
	public ArrayList<Ligne> getReseauMetro() {
		Statement stmt1 = jdbc.getStatement();
		String sql = "Select * from Ligne;";
		ArrayList<Ligne> lstLigne = new ArrayList<Ligne>();
		ResultSet rs, resultLigne;
		try {
			rs = stmt1.executeQuery(sql);

			while(rs.next()){
				String idLigne = rs.getString("idLigne");
				Ligne ligne = new Ligne();
				ligne.setNom(rs.getString("nomLigne"));
				ligne.setCouleur(rs.getString("codeCouleur"));
				ligne.setUrlImage(rs.getString("urlLogo"));
				ligne.setIdLigne(idLigne);

				Statement stmt2 = jdbc.getStatement();
				String sql2 = "SELECT S.nomStation FROM LigneStation LS, Station S WHERE LS.idStation = S.idStation AND LS.idLigne = " + idLigne  +" ORDER BY LS.ordre;";
				resultLigne = stmt2.executeQuery(sql2);
				ArrayList<Station> lstStation = new ArrayList<Station>(); 
				while(resultLigne.next()){
					Station station = new Station();
					station.setName(resultLigne.getString("nomStation"));
					station.setLongitude("longitude");
					station.setLatitude("latitude");
					lstStation.add(station);
				}
				if(lstStation.size() > 0)
					ligne.setDirection(lstStation.get(lstStation.size() - 1));
				ligne.setLigne(lstStation);
				lstLigne.add(ligne);
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return lstLigne;
	}

	@Override
	public ArrayList<Etape> searchTrajet(Station depart, Station arrive) {
		//TODO Implementer Dijkstrah
		return null;
	}

}
